package com.mj.listen1._02链表;

public class SingleLinkList<E> extends AbstractList<E> {

    private Node<E> first;

    private static class Node<E> {
        private E element;
        private Node<E> next;

        public Node(E element, Node<E> next) {
            this.element = element;
            this.next = next;
        }
    }

    @Override
    public void clear() {
        size = 0;
        first = null;
    }

    @Override
    public E get(int index) {
        return node(index).element;
    }

    @Override
    public E set(int index, E element) {
        // 找到index位置的node，然后修改
        Node<E> node = node(index);
        node.element = element;
        return node.element;
    }

    @Override
    public void add(int index, E element) {
        rangeCheckForAdd(index);
        if (index == 0) {
            // 新的节点指向原来头节点的next
            Node<E> newNode = new Node<>(element, first);
            // 头指针指向新的头节点
            first = newNode;
        } else {
            Node<E> pre = node(index - 1);
            Node<E> newNode = new Node<>(element, pre.next);
            pre.next = newNode;
        }
        size++;
    }

    @Override
    public E remove(int index) {
        rangeCheck(index);
        Node<E> current = first;
        if (index == 0) {
            // 头指针换一下位置，指向下一个节点
            first = first.next;
        } else {
            // 找到index索引位置的前一个节点
            Node<E> pre = node(index - 1);
            current = pre.next;
            // 前一个节点的next指向它的下下个节点
            pre.next = current.next;
        }
        size--;
        return current.element;
    }

    @Override
    public int indexOf(E element) {
        Node<E> node = first;
        if (element == null) {
            for (int i = 0; i < size; i++) {
                if (null == node) {
                    return i;
                }
                node = node.next;
            }
        } else {
            for (int i = 0; i < size; i++) {
                if (element == node.element) {
                    return i;
                }
                node = node.next;
            }
        }
        return ELEMENT_NOT_FOUND;
    }

    /**
     * 找到index位置的node
     *
     * @param index
     * @return
     */
    public Node<E> node(int index) {
        rangeCheck(index);
        Node<E> node = first;
        for (int i = 0; i < index; i++) {
            node = node.next;
        }
        return node;
    }

    @Override
    public String toString() {
        StringBuilder sb = new StringBuilder();
        sb.append("size:").append(size).append("，[");
        Node<E> node = first;
        for (int i = 0; i < size; i++) {
            if (i != 0) {
                sb.append("，");
            }
            sb.append(node.element);
            node = node.next;
        }
        sb.append("]");
        return sb.toString();
    }
}
